<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-28 11:28:08
 * Desc:
 */

namespace app\base\model\system;

use app\base\model\ModelTrait;
use think\Model;
use app\core\cache\{RedisCache, RedisKeys};

class SystemConfig extends Model
{
    use ModelTrait;

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = false;

    protected $table = 'xy_system.xy_system_config';

    public function __construct($data = [])
    {
        parent::__construct($data);
        RedisCache::selectDB(config('redis_db_index.system'));
    }

    public static function getSystemConfigByName($name, $default = '')
    {
        $key = RedisKeys::getSystemConfigHashKey($name);
        if (!RedisCache::hExists($key, 'value')) {
            $row = self::getSystemConfigInfo($name);
            return $row['value'] ?? $default;
        } else {
            return RedisCache::hGet($key, 'value');
        }
    }

    public static function getSystemConfigInfo($name)
    {
        $key = RedisKeys::getSystemConfigHashKey($name);
        if (!RedisCache::exists($key)) {
            $row = self::where('name', $name)->find();
            if ($row) {
                $row = $row->toArray();
                RedisCache::hMset($key, $row);
            }
        }
        return RedisCache::hGetAll($key);
    }

    public static function getSystemConfigList($where, $page_size = 15)
    {
        $items = self::where($where)
            ->order('id', 'desc')
            ->paginate($page_size)->toArray();

        return $items;
    }

    public static function delCache($name)
    {
        $key = RedisKeys::getSystemConfigHashKey($name);
        RedisCache::del($key);
        return self::getSystemConfigInfo($name);
    }

    /**
     * Desc: 获取新用户赠送的心愿值
     * Date: 2020/2/21 21:11
     * Author: yiyu
     * @return bool|string
     */
    public static function getNewUserGiveWishCoinNum()
    {
        return SystemConfig::getSystemConfigByName('register_give_wish_coin_num', 9.9);
    }

    /**
     * Desc: 获取心愿值的作用
     * Date: 2020/2/21 21:10
     * Author: yiyu
     */
    public static function getWishCoinEffect()
    {
        return self::getSystemConfigByName('wish_coin_effect', '心愿值可兑换等值好物心愿');
    }


}